#include "RegisterTask.h"

RegisterTask::RegisterTask(char* body, int client_fd, int len, int shmid, int msgid):BaseTask(body, client_fd, len, shmid, msgid)
{

}

void RegisterTask::working()
{	
	REGISTER_REQ register_req = { 0 };
	User user = { 0 };
	//拷贝获取请求信息
	memcpy(&register_req, body, sizeof(REGISTER_REQ));
	user = register_req.user;
	cout << "------------------------操作日志------------------" << endl;
	// 获取当前时间点（系统时钟）
	auto now = std::chrono::system_clock::now();
	auto in_time_t = std::chrono::system_clock::to_time_t(now);
	std::stringstream ss;
	ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %H:%M:%S");
	cout << "时间: " << ss.str();  // ctime自带换行
	cout << "功能：注册" << endl;
	cout << "类型：接收" << endl;
	cout << "用户：" <<user.username<< endl;
	cout << "发送数据包：" << endl;
	cout << "用户手机号:" << user.phonenumber << "\n"
		<< "用户头像:" << user.imgpath << "\n"
		<<"用户密码:"<<user.userpass<<"\n"
		<<"手机验证码:"<< register_req.core<<endl;

	//写入文件
	LogManager& log_fd = LogManager::getInstance();
	ofstream& fd = log_fd.getLogStream();
	fd << "时间: " << ss.str()<<"\n"  // ctime自带换行
	<< "功能：注册\n"
	<< "类型：接收\n"
	<< "用户：" << user.username <<"\n"
	<< "发送数据包：\n" 
	<< "用户手机号:" << user.phonenumber << "\n"
	<< "用户头像:" << user.imgpath << "\n"
	<< "用户密码:" << user.userpass << "\n"
	<< "手机验证码:" << register_req.core <<"\n"
	<< "--------------------------------------------" << "\n\n";
	// 4. 强制刷新缓冲区（确保日志立即写入文件）
	fd.flush();

	//校验	
	std::string name(user.username);
	std::string phone(user.phonenumber);
	if (checkUser(name,phone)==true)
	{
		if (checkCode(user, register_req.core)==true)
		{
			//写入数据库
			if (model->insetUser(user))
			{
				send(Success, "注册：注册成功",user.username);
			}
		}
	}
}

bool RegisterTask::checkCode(User& user ,char* core)
{
	std::string str(core);
	if (str==Codemap[atoi(user.phonenumber)])
	{
		return true;
	}
	else
	{
		send(Failure, "注册：验证码错误", user.username);
		return false;
	}

}

bool RegisterTask::checkUser(string &name,string &phone)
{
	shared_ptr<User> user = model->getUser(name, phone);
	if (user==nullptr)//返回的用户名不为空
	{
		return true;
	}		
	send(Failure, "注册：用户名已存在 ", name);
	return false;
}

void RegisterTask::send(int statu, string message, string name)
{
	ShmControl* shm = (ShmControl*)shmat(shmid, NULL, 0);
	int index = -1;//空闲下标
	// 寻找下一个空闲块（状态0）
	for (int i = 0; i < MEMORYNUMBER; i++) {
		int status = shm->blocks[i].status;
		if (status == 0) { // 空闲
			index = i;
			break;
		}
	}
	HEAD head = { 0 };
	RESP resp = { 0 };//响应
	char send[MEMORYSIZE] = { 0 };
	strcpy(resp.message, message.c_str());
	resp.status_code = statu;
	//写头
	head.service_type = REGISTER;
	head.checksum = 100;
	head.data_len = sizeof(RESP);
	//头体结合
	memcpy(send, &head, sizeof(HEAD));
	memcpy(send + sizeof(HEAD), &resp, sizeof(RESP));

	//写入共享内存
	sem_p(sem_shm, 0);//获取共享内存锁
	ShmBlock* block = &shm->blocks[index];
	memcpy(block->data, send, sizeof(block->data));//考入共享内存
	block->status = 1;                   // 标记为已写
	shmdt(shm);
	sem_v(sem_shm, 0);//释放共享内存锁

	//写入消息队列
	MSG msg = { 0 };
	msg.client_fd = client_fd;
	msg.index = index;
	msg.mtype = 1;
	msgsnd(msgid, &msg, sizeof(MSG), 0);	
	cout << "------------------------操作日志------------------" << endl;
	// 获取当前时间点（系统时钟）
	auto now = std::chrono::system_clock::now();
	auto in_time_t = std::chrono::system_clock::to_time_t(now);
	std::stringstream ss;
	ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %H:%M:%S");
	cout << "时间: " << ss.str();  // ctime自带换行
	cout << "功能：注册" << endl;
	cout << "类型：发送" << endl;
	cout << "用户："<< endl;
	cout << "发送数据包：" << endl;
	cout << "状态:" << statu << "\n"
		<< "信息:" << message << endl;

	//写入文件
	LogManager& log_fd = LogManager::getInstance();
	ofstream& fd = log_fd.getLogStream();
	fd<< "时间: " << ss.str()<<"\n"  // ctime自带换行
	<< "功能：注册\n"
	<< "类型：发送\n"
	<< "发送数据包：\n"
	<<"用户:"<<name<<"\n"
	<< "状态:" << statu << "\n"
	<< "信息:" << message << "\n"
	<< "--------------------------------------------" << "\n\n";
	// 4. 强制刷新缓冲区（确保日志立即写入文件）
	fd.flush();
}
